package cn.itcast.web.controller.system;

import cn.itcast.domain.system.Dept;
import cn.itcast.service.system.DeptService;
import cn.itcast.web.controller.BaseController;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;

@Controller
@RequestMapping("/system/dept")
public class DeptController extends BaseController {

 @Autowired
 private DeptService deptService;

 /**
  * 分页查看所有部门
  */
 @RequestMapping("/list")
 public String list(
  @RequestParam(defaultValue = "1") int page,
  @RequestParam(defaultValue = "10") int size
 ) {
  //获取当前用户的企业id
  String companyId = getLoginCompanyId();
  //调用service查询分页列表数据
  PageInfo info = deptService.findAll(companyId,page,size);
  //数据保存到request域
  request.setAttribute("page",info);
  return "system/dept/dept-list";
 }

 /**
  * 进入保存部门页面
  */
 @RequestMapping("/toAdd")
 public String toAdd() {
  //查询所有部门，为了构造下拉框，不分页
  String companyId = getLoginCompanyId();
  List list = deptService.findAll(companyId);
  //部门列表存入request域
  request.setAttribute("deptList",list);
  //跳转页面
  return "system/dept/dept-add";
 }

 /**
  * 保存或修改部门
  */
 @RequestMapping("/edit")
 public String edit(Dept dept) {
  //设置部门的企业参数
  dept.setCompanyId(getLoginCompanyId());
  dept.setCompanyName(getLoginCompanyName());
  //判断dept对象中是否包含id
  if (StringUtils.isEmpty(dept.getId())) {
   //不存在id，保存
   deptService.save(dept);
  }else {
   //存在id，更新
   deptService.update(dept);
  }
  //页面重定向到列表
  return "redirect:/system/dept/list.do";
 }

 /**
  * 进入修改页面
  */
 @RequestMapping("/toUpdate")
 public String toUpdate(String id) {
  //调用service查询id
  Dept dept = deptService.findById(id);
  //存入request域
  request.setAttribute("dept",dept);
  //查看所有部门
  String companyId = getLoginCompanyId();
  List<Dept> list = deptService.findAll(companyId);
  //将部门存入request域
  request.setAttribute("deptList",list);
  //跳转更新页面
  return "system/dept/dept-update";
 }

 /**
  * 根据id删除
  */
 @RequestMapping("/delete")
 public String delete(String id) {
  deptService.delete(id);
  return "redirect:/system/dept/list.do";
 }
}
